package demo02_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kunkun
 * @className TicketSolution_pro
 * @Description 解决买票问题
 * @date 2025/3/5 16:11
 */
public class TicketSolution_pro {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{while (ticket.ticketsNum>0) ticket.sail();},"A").start();
        new Thread(()->{while (ticket.ticketsNum>0) ticket.sail();},"B").start();
        new Thread(()->{while (ticket.ticketsNum>0) ticket.sail();},"C").start();
    }


    static class Ticket {

        private int ticketsNum = 20;

        private Lock lock = new ReentrantLock(false);   //true:公平锁，false:非公平锁（默认）

        public void sail() {
            lock.lock();
            try{
                if (ticketsNum > 0){
                    System.out.println(Thread.currentThread().getName()+"购买第" + ticketsNum + "张票，剩余" + (ticketsNum--) + "张票");
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

}

